const router = require('koa-router')(); //引入router 并调用
const ObjectId = require('mongodb').ObjectId
const mongo = require('../compents/mongo')
const { postLogData } = require("../utils/misc")
    // 设置根路径
router.prefix('/staff')

// 保存数据时间
const nowTime = function getTime() {
    let date = new Date();
    Y = date.getFullYear() + '-';
    M = zeroFill(date.getMonth() + 1) + '-';
    D = zeroFill(date.getDate()) + ' ';
    h = zeroFill(date.getHours()) + ':';
    m = zeroFill(date.getMinutes()) + ':';
    s = zeroFill(date.getSeconds());
    return (Y + M + D + h + m + s)
}

// 补零
function zeroFill(n) {
    return n < 10 ? "0" + n : n
}


// 测试用端口
router.get('/test', async ctx => {
    console.log(ctx);
    ctx.body = 'test'
})

// 获取后台数据
router.get('/list', async ctx => {
    postLogData("请求员工管理")
    let { limit, page, where } = ctx.query
    const res = await mongo.find('staff', { limit: limit * 1, page: page * 1 })
    const total = await mongo.count('staff', { where })
    ctx.body = { data: res, code: 20000, total, message: "端口求成功" }
})

// 保存数据
router.post('/save', async ctx => {
    postLogData("新增员工管理")
    const res = await mongo.insertOne('staff', {...ctx.request.body, dataTime: nowTime() })
    if (res.insertedId) {
        ctx.body = { data: res, code: 20000, message: "数据插入成功" };
    } else {
        ctx.body = { data: res, code: 50001, message: "数据插入失败" };
    }
})

// 修改数据
router.post('/change', async ctx => {
    postLogData("修改员工管理")
    const { _id } = ctx.request.body
    const update = ctx.request.body
    delete update._id
    const res = await mongo.updateOne('staff', { where: { _id: ObjectId(_id) }, update })
    if (res.modifiedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据修改成功" };
    } else {
        ctx.body = { data: res, code: 50002, message: "数据修改失败" };
    }

})

// 删除单挑数据
router.get('/delOne', async ctx => {
    postLogData("单删员工管理")
    const { _id } = ctx.query
    const res = await mongo.deleteOne('staff', { _id: ObjectId(_id) })
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据删除成功" };
    } else {
        ctx.body = { data: res, code: 50003, message: "数据删除失败" };
    }
})

// 删除多条数据
router.get('/delMany', async ctx => {
    postLogData("多删员工管理")
    let { ids } = ctx.query
    console.log(ids);
    ids = JSON.parse(ids)
    const res = await mongo.deleteMany('staff', ids)
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据批量删除成功" };
    } else {
        ctx.body = { data: res, code: 50004, message: "数据批量删除失败" };
    }
})

// 查询
router.get('/search', async ctx => {
    let { id } = ctx.query
    let where = { _id: ObjectId(id) }
    const res = await mongo.findOne('staff', where)
    console.log(res);
    ctx.body = { code: 20000, data: res, message: '接口请求成功' }
})


module.exports = router //导出路由对象